package cn.edu.sjtu.gateway.util;

import cn.edu.sjtu.gateway.model.RespStatus;
import cn.edu.sjtu.gateway.model.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;

/**
 * @author loumoon
 * @date 2019-10-21 00:16
 */
public class ResultUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static Result success(Object data) {
        return Result.builder()
                .status(RespStatus.SUCCESS.getCode())
                .message(RespStatus.SUCCESS.getMessage())
                .data(data)
                .build();
    }

    public static Result success() {
        return success(null);
    }

    public static Result error(RespStatus status) {
        return Result.builder()
                .status(status.getCode())
                .message(status.getMessage())
                .build();
    }

    public static Mono<Void> writeError(ServerWebExchange exchange, RespStatus status) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add(CONTENT_TYPE, APPLICATION_JSON_VALUE);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        try {
            return response.writeWith(
                    Flux.just(response.bufferFactory()
                            .wrap(mapper.writeValueAsBytes(error(status)))));
        } catch (JsonProcessingException e) {
            return response.setComplete();
        }
    }
}
